//去掉空格
function trim(value) {
    if (value) {
        value = value.replace(/^\s*|\s*$/g, "");
    }
    if (!value) {
        return "";
    } else {
        return value;
    }
}

// 对参数编码
function encodeStr(val) {
    return encodeURIComponent(encodeURIComponent(trim(val)));
}

// 对参数解码
function decodeStr(val) {
    return decodeURIComponent(decodeURIComponent(trim(val)));
}

// 新窗口打开页面
function openWindow(url, name, iWidth, iHeight, data) {
    url = getRootPath() + url;
    if (data && data !== '') {
        url += "&data=" + encodeStr(JSON.stringify(data));
    }
    //window.screen.height获得屏幕的高，window.screen.width获得屏幕的宽
    var iTop = (window.screen.height - iHeight) / 2;       //获得窗口的垂直位置;
    var iLeft = (window.screen.width - iWidth) / 2;        //获得窗口的水平位置;
    window.open(url, name, 'height=' + iHeight + ',innerHeight=' + iHeight + ',width=' + iWidth + ',innerWidth=' + iWidth + ',top=' + iTop + ',left=' + iLeft + ',toolbar=no,menubar=no,scrollbars=auto,location=no,status=no');
}

//验证必填信息, 返回必填项信息
function verify(jqueryObj) {
    var msg = [];
    jqueryObj.find('.needCheck').each(function (key, value) {
        var name = $(value).attr("name");
        if ($(value).attr('type') == 'checkbox') {
            if ($('input[name=' + name + ']:checked').size() < 1) {
                msg.push($(value).attr('msg'));
            }
        } else if ($(value).attr('type') == 'radio') {
            if ($('input[name=' + name + ']:checked').size() < 1) {
                msg.push($(value).attr('msg'));
            }
        } else {
            if (!trim($(value).val())) {
                msg.push($(value).attr('msg'));
            }
        }
    });
    return msg;
}

function myAjax(options) {
    options = options || {};
    options.type = (options.type || "GET").toUpperCase();
    options.dataType = options.dataType || "json";
    options.async = options.async || true;
    options.data = options.data || {};
    options.contentType = options.contentType || "application/x-www-form-urlencoded";
    if ("GET" === options.type) {
        options.data["time"] = Date.now();
        for (var param in options.data) {
            if (options.data.hasOwnProperty(param)) {
                if (typeof options.data[param] === "string") {
                    options.data[param] = encodeStr(options.data[param]);
                }
            }
        }
    }
    console.log(options);
    $.ajax({
        url: getRootPath() + options.url,
        type: options.type,
        headers: {'token': getCookie("token")},
        dataType: options.dataType,
        async: options.async,
        data: options.data,
        contentType: options.contentType,
        success: function(res) {
            if (options.dataType === "json") {
                console.log(res);
                if (res && res.code == 914) {
                    alert(res.msg);
                    window.location.href=getRootPath() + res.data;
                }  else {
                    options.mySuccess(res);
                }
            } else if ($("#code") && $("#code").val() == 914) {
                alert($("#msg") ? $("#msg").val() : "似乎出了点问题");
                window.location.href = getRootPath();
            } else {
                options.mySuccess(res);
            }
        },
        error: function() {
            alert("服务器异常，请稍后重试");
        }
    })
}

//设置cookie
function setCookie(name, value, day) {
    var date = new Date();
    date.setDate(date.getDate() + day);
    document.cookie = name + '=' + value + ';expires=' + date;
}

//获取cookie
function getCookie(name) {
    var reg = RegExp(name + '=([^;]+)');
    var arr = document.cookie.match(reg);
    if (arr) {
        return arr[1];
    } else {
        return '';
    }
}

//删除cookie
function delCookie(name) {
    setCookie(name, null, -1);
}

function getRootPath(){
    //获取当前网址，如： http://localhost:8080/jsp/userlist.jsp
    var curWwwPath=window.document.location.href;
    //获取主机地址之后的目录，如： jsp/userlist.jsp
    var pathName=window.document.location.pathname;
    var pos=curWwwPath.indexOf(pathName);
    //获取主机地址，如： http://localhost:8080
    var localhostPaht=curWwwPath.substring(0,pos);
    //获取带"/"的项目名，如：/jsp
    var projectName=pathName.substring(0,pathName.substr(1).indexOf('/')+1);
    return (localhostPaht+projectName);
}

(function($){
    $.fn.serializeJson=function(){
        var serializeObj={};
        var array=this.serializeArray();
        var str=this.serialize();
        $(array).each(function(){
            if(serializeObj[this.name]){
                if($.isArray(serializeObj[this.name])){
                    serializeObj[this.name].push(this.value);
                }else{
                    serializeObj[this.name]=[serializeObj[this.name],this.value];
                }
            }else{
                serializeObj[this.name]=this.value;
            }
        });
        return serializeObj;
    };
})(jQuery);